# -*- coding: utf-8 -*-
import requests
from lxml import etree
from tools.mysqlconn import NBAdb
from mysql_text import sql_insert_text
from tools.auxiliary_tool import normalization


class Name:

    def __init__(self):
        """
        初始化一些东西。
        """
        # 解析HTML
        self.headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
        }
        res = requests.get('http://www.stat-nba.com/teamList.php', headers=self.headers)
        res.encoding = 'utf-8'
        self.html = etree.HTML(res.text)

    def get_active_team(self):
        """
        获取现役球队
        :return:
        """
        one = NBAdb()

        dic_one = {1: '东南区', 2: '中区', 3: '大西洋区', 4: '太平洋区', 5: '西北区', 6: '西南区'}

        content_one = self.html.xpath('//div[@class="stat_box"]/table//td')

        a = 1
        for item in content_one:
            team_name = item.xpath('.//a//text()')
            if 1 <= a <= 3:
                team_area = '东部'
                for i in team_name:
                    list_name = [i, dic_one[a], team_area]
                    # 插入数据
                    one.insert_table(sql_insert_text.insert_nba_active_team, list_name)
                a += 1
            elif 4 <= a <= 6:
                team_area = '西部'
                for i in team_name:
                    list_name = [i, dic_one[a], team_area]
                    # 插入数据
                    one.insert_table(sql_insert_text.insert_nba_active_team, list_name)
                a += 1
            else:
                pass
        # 释放资源
        del one

    def get_history_team(self):
        """
        获取历史球队
        :return:
        """
        one = NBAdb()
        content_two = self.html.xpath('//div[@class="teamList"]//a//text()')
        for item in normalization(content_two):
            one.insert_table(sql_insert_text.insert_nba_history_team, [item])
        # 释放资源
        del one


if __name__ == '__main__':
    print('ok')
